<?php
//个人中心
namespace App\Http\Controllers\App;
use App\Http\Controllers\App\BaseController as Controller;
use App\Models\CashConfig;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\WalletLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Zhuzhichao\BankCardInfo\BankCard;

class UserController extends Controller
{
    public function __construct(Request $request)
    {
        $checkThisClerk = $this->getShopUserID($request->token,$request->device_id);
        if(!$checkThisClerk){
            return show(2001,'无效token');
        }else{//判断用户角色
            //权限处理
            switch($checkThisClerk->role){
                case -1:
                    $this->thisLoginClerk = $checkThisClerk;
                    break;
                case 0:
                case 1:
                case 2:
                case 3:
                    return show(2002,'没有权限');
                    break;
                default:
                    return show(2002,'没有权限');
                    break;
            }
        }
    }
    //提现
    public function withdraw(Request $request)
    {
        $rules = [
            'id' => 'required|exists:cash_configs,id',
            'money'=>'required',
        ];
        $message = [
            'id.*'=>'请选择正确的提现账号',
            'money.*'=>'请选择正确的金额',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }

        $user_id= $this->thisLoginClerk->id;
        $mUser = User::find($user_id);
        if (!in_array($mUser->role,['2','1'])){
            return show(2003,'请先注册成为平台商家');
        }
        $money = $mUser->money;
        if ($money < $request->money){
            return show(2003,'提现金额不足');
        }
        $userinfo = UserInfo::where('user_id',$user_id)->first();
        if($userinfo['real_name']==''){
            return show(201,'请先实名认证');
        }
        $id = $request->id;
        //@todo 判断这个提现账户是否属于对应用户
        $cashConfig = CashConfig::where('status',1)->where('user_id',$user_id)->find($id);
//        dd($cashConfig);
        if (!$cashConfig){
            return show(2003,'请选择正确的提现账号');
        }
        DB::beginTransaction();
        try{
            $data = array(
                'user_id'=>$user_id,
                'bank'=>$cashConfig->bank_type,
                'bank_account'=>$cashConfig->account_number,
                'real_name'=>$userinfo['real_name'],
                'money'=>$request->money,
                'cash_status'=>0,
                'created_at'=>date("Y-m-d H:i:s"),
                'updated_at'=>date("Y-m-d H:i:s")
            );
            $resulta = DB::table('cashs')->insert($data);
            // 多多少少留下点，不然出现问题就不好了,将提现的金额减少
            $resultb = DB::table('users')->where('id',$user_id)->decrement('money',$request->money);
            $now_money = DB::table('users')->find($user_id,['money']);
//            dd($now_money);
            if($resulta && $resultb)
            {
                DB::commit();
                return show(200,'申请提现成功，请耐心等待',$now_money);
            }
        }catch (\Exception $e){
            DB::rollBack();
            dd($e->getMessage());
            return show(201,'申请提现失败，请联系客服或重试');
        }

    }

    //添加银行卡
    public function addCard(Request $request)
    {
        $rules = [
            'account_number' => 'required|unique:cash_configs,account_number',
            'account_user' => 'required',
//            'bank'=>'required',
            'bank_type'=>'required|integer'
        ];
        $message = [
            'account_number.required'=>'请输入正确银行卡号',
            'account_number.unique'=>'该银行卡已存在',
            'account_user.*'=>'请输入正确姓名',
//            'bank.*'=>'请选择正确的银行',
            'bank_type.*'=>'请选择正确所属银行'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        try{
//            {
//                "validated": true,
//                "bank": "CMB",
//                "bankName": "招商银行",
//                "bankImg": "https://apimg.alipay.com/combo.png?d=cashier&t=CMB",
//                "cardType": "CC",
//                "cardTypeName": "信用卡"
//            }
//            失败返回
//            {
//                "validated": false,
//            }
//            $info = BankCard::info($request->account_number);

            $user_id= $this->thisLoginClerk->id;
            $data = [
                'account_number'=>$request->account_number,
                'account_user'=>$request->account_user,
//                'bank'=>$request->bank,
                'user_id'=>$user_id,
                'bank_type'=>$request->bank_type
            ];

            $count = UserInfo::where('user_id',$user_id)->count();
            if ($count != 1){
                return show(202,"请先实名认证");
            }
            CashConfig::create($data);
            return show(200,'银行卡添加成功');
        }catch (\Exception $e){
            return show(201,'银行卡添加失败');
        }

    }

    //删除银行卡
    public function deleteCard(Request $request)
    {

        $rules = [
            'id'=>'required|exists:cash_configs,id',
        ];
        $message = [
            'id.*'=>'请选择正确的银行卡'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        $user_id= $this->thisLoginClerk->id;
        $is_yours = CashConfig::where('user_id',$user_id)->find($request->id);
        if (!$is_yours){
            return show(2003,'请选择正确的银行卡');
        }
        $delete = CashConfig::where('id',$request['id'])->delete();
        if($delete){
            return show(200,'删除成功');
        }else{
            return show(201,'删除失败');
        }
    }

    //展示银行卡
    public function showCard()
    {
        $user_id= $this->thisLoginClerk->id;
        $data = CashConfig::where('status',1)->where('user_id',$user_id)->orderBy('created_at','desc')->get(['id','account_type','account_number','account_user','bank_type']);
        if($data->isEmpty()){
            return show(201,'暂无银行卡');
        }
        return show(200,'信息获取成功',$data);
    }

    // 明细流水
    public function funds(Request $request){
        $rules = [
            'type'=>'integer|in:0,1'
        ];
        $message = [
            'type.*'=>'请选择正确的消费类型'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        try{
            $user_id = $this->thisLoginClerk->id;
            $perPage = 15;
            if (isset($request->type)){
                $res = WalletLog::where('user_id',$user_id)->where('type',$request->type);
            }else{
                $res = WalletLog::where('user_id',$user_id);
            }
            $res = $res->orderBy('created_at','desc')->paginate($perPage,['id','type','serial_number','work_capital','sign','created_at']);
            if ($res->isEmpty()){
                return show(201,'暂无明细');
            }
        }catch (\Exception $e){
            return show(201,'暂无明细');
        }
        return show(200,'明细信息',$res);
    }

    // 展示用户的所有金额
    public function showMoney()
    {
        $user_id= $this->thisLoginClerk->id;
        $now_money = DB::table('users')->find($user_id,['money']);

        return show(200,'信息获取成功',$now_money);
    }
    // 实名认证
    public function identify(Request $request){
        $rules = [
            'realname'=>'required|string',
            'cardno' =>'required|identitycards|unique:user_infos,id_card',
        ];
        $message = [
            'realname.*'=>'请填写真实姓名',
            'cardno.unique'=>'该身份证号已经存在',
            'cardno.identitycards'=>'请填写正确的身份证号',
            'cardno.required'=>'请填写正确的身份证号',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        $realName = $request->realname;
        $cardNo = $request->cardno;

        $user_id = $this->thisLoginClerk->id;
        $count = UserInfo::where('user_id',$user_id)->count();
        if ($count == 1){
            return show(2003,"该用户已经实名认证！");
        }

        $realName=urlencode($realName);
        $host= "http://1.api.apistore.cn";
        $path = "/idcard";
        $method = "GET";
        $appcode = "359b0e04dd374def9ddcc148bfe586a5";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "cardNo=".$cardNo."&realName=".$realName;
        $bodys = "";
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $result = curl_exec($curl);
        $result = json_decode($result,true);

        try{
            if ($result['error_code'] == '0'){
                UserInfo::create([
                    'user_id'=>$user_id,
                    'real_name'=>$result['result']['realName'],
                    'id_card'=>$result['result']['cardNo']
                ]);
                return show(200,'实名认证成功');
            }else{
                return show(201,'实名认证失败');
            }
        }catch (\Exception $e){
            return show(201,'实名认证失败');
        }
    }
    // 检查是否已经实名认证过了
    public function checkIdentify(){
       $user_id = $this->thisLoginClerk->id;
       $user = DB::table('user_infos')->where('user_id',$user_id)->first();//['id_card as cardNo','real_name as realName']);

       if ($user && ($user->id_card != '')){
           $result['cardNo'] = $user->id_card;
           $result['realName'] = $user->real_name;
           return show(200,'已实名认证',$result);
       }else{
           return show(201,'还未实名认证');
       }

    }
}
